﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Principal;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using WebApp.BLL.Service;

namespace WY.WebApi
{
    public class APIAuthorizeFilterAttribute : AuthorizationFilterAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            //base.OnAuthorization(actionContext);

            //如果请求方法为Options，则不进行授权验证
            if ("Options".Equals(actionContext.ActionDescriptor.ActionName, StringComparison.OrdinalIgnoreCase))
            {
                return;
            }
            //如果用户方位的Action带有AllowAnonymousAttribute，则不进行授权验证
            if (actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any())
            {
                return;
            }

            bool verifyResult = false;
            if (actionContext.Request.Headers.Authorization != null)
            {
                //验证token有效性
                var token = new AccessTokenService().CheckAccessToken(actionContext.Request.Headers.Authorization.Parameter);
                if (token != null)
                {
                    verifyResult = true;

                    //设置身份信息
                    var userIdentity = new GenericIdentity(token.userId);
                    var principal = new GenericPrincipal(userIdentity, null);
                    actionContext.RequestContext.Principal = principal;
                }
            }
            //var verifyResult = actionContext.Request.Headers.Authorization != null &&  //要求请求中需要带有Authorization头
            //                   actionContext.Request.Headers.Authorization.Parameter == "123456"; //并且Authorization参数为123456则验证通过

            if (!verifyResult)
            {
                //如果验证不通过，则返回401错误，并且Body中写入错误原因
                actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, new HttpError("已拒绝为此请求授权。"));

                var host = actionContext.Request.RequestUri.DnsSafeHost;
                //actionContext.Response = new HttpResponseMessage { StatusCode = System.Net.HttpStatusCode.Unauthorized, ReasonPhrase = "已拒绝为此请求授权。" };
                //actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
                actionContext.Response.Headers.Add("WWW-Authenticate", string.Format("Basic realm=\"{0}\"", host));
            }
        }
    }
}